import { Breadcrumb, Button, Card, Form, Input, Radio } from "antd";
import Channel from "components/Channel";
import { Link } from "react-router-dom";
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import styles from './index.module.scss'

import { Upload, message, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { useEffect, useRef, useState } from 'react';
import { addArticleAPI, getArticleById, updateArticle } from "api/articles";
import history from "utils/history";


export default function ArticlePublish({ match }) {
    const id = match.params.id

    const getArticle = async () => {
        const res = await getArticleById(id)
        console.log(res.data);
        const { title, channel_id, content, cover } = res.data
        formRef.current.setFieldsValue({ title, channel_id, content })
        setCoverType(cover.type)
        setImages(cover.images.map((item) => ({ url: item })))
    }

    const formRef = useRef(null)

    useEffect(() => {
        if (id) {
            getArticle()
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const draftRef = useRef(false)
    // 提交表单
    const onFinish = async (value) => {
        if (coverType !== images.length) {
            message.warn('请上传正确数量的封面')
            return
        }
        const reqParams = {
            ...value,
            cover: {
                type: coverType,
                images: images.map(item => item.url || item.response.data.url)
            },
            draft: draftRef.current
        }
        if (id) {
            reqParams.id = id
            await updateArticle(reqParams)
        } else {
            await addArticleAPI(reqParams)
        }
        message.success(`${id ? '编辑' : '发布'}成功`, 1)
        history.push('/list')
    }

    const [images, setImages] = useState([])
    const props = {
        fileList: images,
        accept: '.png,.jpg,.jpeg',
        name: 'image',
        action: baseURL + '/upload',
        headers: {
            authorization: 'Bearer ' + getToken(),
        },
        onChange({ file, fileList }) {
            setImages(fileList)
            if (file.status === 'done') {
                message.success(`${file.name} 上传成功`);
            } else if (file.status === 'error') {
                message.error(`${file.name} 上传失败`);
            }
        },
        // 上传前,可以鉴定上传的图片类型
        beforeUpload: file => {
            const isType = ['image/jpeg', 'image/jpg', 'image/png'].includes(file.type)
            if (!isType) {
                message.error(`${file.name} is not a png file`);
            }
            return isType ? true : Upload.LIST_IGNORE;
        },
        // 点击预览图片
        onPreview: file => {
            setPreviewImage(file.thumbUrl || file.url)
        }
    };
    const [previewImage, setPreviewImage] = useState('')
    const [coverType, setCoverType] = useState(1)
    const coverTypeChange = (value) => {
        setCoverType(value)
        setImages([])
    }
    return (
        <div className={styles.publish}>
            <Card
                title={
                    <Breadcrumb separator=">">
                        <Breadcrumb.Item>
                            <Link to="/home">首页</Link>
                        </Breadcrumb.Item>
                        {id ? <Breadcrumb.Item>
                            <Link to="/list">文章列表</Link>
                        </Breadcrumb.Item> : null}
                        <Breadcrumb.Item>{id ? '编辑' : '发布'}文章</Breadcrumb.Item>
                    </Breadcrumb>
                }
            >
                <Form
                    ref={formRef}
                    labelCol={{ span: 4 }}
                    onFinish={onFinish}
                    initialValues={{ content: '' }}
                    validateTrigger={['onBlur', 'onChange']}>
                    <Form.Item label='标题' name='title' rules={[{ required: true, message: '请输入文章标题' }]} >
                        <Input placeholder='请输入文章标题' />
                    </Form.Item>
                    <Form.Item label="频道" name='channel_id' rules={[{ required: true, message: '请输入频道' }]}>
                        <Channel />
                    </Form.Item>
                    <Form.Item label='内容' name='content'
                        rules={[
                            { required: true, message: '请输入文章内容' }, {
                                validator: (_, value) => {
                                    return value === '<p><br></p>' ? Promise.reject('请输入文章内容') : Promise.resolve()
                                }
                            }
                        ]}
                    >
                        <ReactQuill
                            theme="snow"
                            placeholder="请输入文章内容..."
                        ></ReactQuill>
                    </Form.Item>
                    <Form.Item label='封面'>
                        <Radio.Group value={coverType} onChange={(e) => coverTypeChange(e.target.value)}>
                            <Radio value={1}>单图</Radio>
                            <Radio value={3}>三图</Radio>
                            <Radio value={0}>无图</Radio>
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Upload {...props} listType='picture-card' >
                            {images.length < coverType ? <PlusOutlined /> : null}
                        </Upload>,
                        {/* 预览图片弹出框 */}
                        <Modal
                            visible={previewImage !== ''}
                            title={'预览图片'}
                            footer={null}
                            onCancel={() => setPreviewImage('')}
                        >
                            <img alt="example" style={{ width: '100%' }} src={previewImage} />
                        </Modal>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 4 }}>
                        <Button type='primary' htmlType='submit'>{id ? '编辑' : '发布'}文章</Button>
                        <Button htmlType='submit' onClick={() => { draftRef.current = true }}>存草稿</Button>
                    </Form.Item>
                </Form>
            </Card>
        </div>
    )
}
